import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:tapped/tapped.dart';
import 'package:verse_systems/pages/lucky/lucky_wheel_contrl.dart';
import 'package:verse_systems/res/colors.dart';
import 'package:verse_systems/utils/image_utils.dart';
import 'dart:math';

class LuckyWheelPage extends StatefulWidget {
  const LuckyWheelPage({super.key});

  @override
  State<LuckyWheelPage> createState() => _LuckyWheelPageState();
}

class _LuckyWheelPageState extends State<LuckyWheelPage>
    with TickerProviderStateMixin {
  final control = Get.put(LuckyWheelContrl());
  final state = Get.find<LuckyWheelContrl>().state;

  late AnimationController animationController;
  late Animation<double> _animation;

  //是否正在转动
  bool isRunning = false;
  //是否顺时针
  bool isClockwise = true;
  //奖品数量
  int prizeNum = 8;
  //最少转动圈数
  int cyclesNum = 4;

  @override
  void initState() {
    super.initState();
    animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 2000),
    );
    //动画监听
    animationController.addListener(() {
      if (animationController.status == AnimationStatus.completed) {
        isRunning = false;
        //结束了
        debugPrint("结束了");
        control.handleLuckyWheel();
      } else if (animationController.status == AnimationStatus.forward) {
        // print('forward');
        debugPrint("forward");
      } else if (animationController.status == AnimationStatus.reverse) {
        // print('reverse');
        debugPrint("reverse");
      }
    });
    //初始位置
    _animation = Tween<double>(begin: 0, end: 0).animate(
      CurvedAnimation(
        parent: animationController,
        curve: const Interval(
          0,
          1.0,
          curve: Curves.easeInToLinear,
        ),
      ),
    );

    // 创建一个从0到360弧度的补间动画 v * 2 * π
  }

  void start() {
    ///中奖编号
    int luckyName = Random().nextInt(8);
    startAnimation(luckyName);
  }

  void buttonOnClickStartRun() {
    if (isRunning == false) {
      isRunning = true;
    } else {
      return;
    }
    start();
  }

  void startAnimation(int index) {
    _animation = Tween<double>(
            begin: 0,
            end: (isClockwise ? 1 : -1) * (cyclesNum + (1 / prizeNum)) * index)
        .animate(CurvedAnimation(
      parent: animationController,
      curve: const Interval(
        0,
        1.0,
        curve: Curves.ease,
      ),
    ));
    setState(() {});
    animationController.reset();
    animationController.forward();

    /*forward()方法表示向前执行一次**/
    /*repeat()方法表示重复执行**/
    /*stop()方法表示暂停执行,暂停到当前进度位置**/
    /*reset()方法表示暂停执行,回到初始位置**reverse:有放大缩小的效果**/
  }

  @override
  void dispose() {
    animationController.stop();
    animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colours.system_background_color,
        body: GetBuilder<LuckyWheelContrl>(
            init: control,
            builder: (_) {
              return Container(
                height: MediaQuery.of(context).size.height,
                width: MediaQuery.of(context).size.width,
                decoration: BoxDecoration(
                  image: DecorationImage(
                      image: ExactAssetImage(
                          ImageUtils.getImgPath("lucky_background")),
                      fit: BoxFit.fill),
                ),
                child: Column(
                  children: [
                    Row(children: [
                      Tapped(
                        child: Container(
                          margin: EdgeInsets.fromLTRB(10.w, 35.w, 0, 0),
                          color: Colors.white.withOpacity(0),
                          padding: const EdgeInsets.symmetric(
                              horizontal: 16, vertical: 16),
                          child: Icon(
                            Icons.arrow_back_ios,
                            color: Colours.app_main_color,
                            size: 22.w,
                          ),
                        ),
                        onTap: () {
                          Get.back();
                        },
                      ),
                    ]),
                    Container(
                      margin: EdgeInsets.fromLTRB(0, 10.w, 0, (Platform.isAndroid)?30.w: 88.w),
                      child: Image.asset(
                        ImageUtils.getImgPath("lucky_banner"),
                        width: 291.w,
                        height: 116.w,
                      ),
                    ),
                    wheelView,
                    Container(
                      width: 330.w,
                      height: 130.w,
                      margin: EdgeInsets.fromLTRB(0, 20.w, 0, 0),
                      padding: EdgeInsets.fromLTRB(16.w, 15.w, 16.w, 25.w),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(12.w)),
                        color: Colours.stringAnAlphaColor("0xff000000",
                            alpha: 0.42),
                        border:
                            Border.all(color: Colours.app_main_color, width: 1),
                      ),
                      child: SingleChildScrollView(
                        child: Text(state.rules_tips.toString(),
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: 13.sp,
                            color: Colours.app_main_color,
                          ))
                      ),
                    )
                  ],
                ),
              );
            }));
  }

  Widget get wheelView {
    return SizedBox(
      width: 300,
      height: 300,
      child: Stack(
        children: [
          Align(
            alignment: Alignment.center,
            child: Image.asset(
              ImageUtils.getImgPath("bg_zhuanpan"),
              width: 300,
            ),
          ),
          Align(
            alignment: Alignment.center,
            child: RotationTransition(
                turns: _animation,
                child: Image.asset(
                  ImageUtils.getImgPath("bg_superjiangpin"),
                  width: 290,
                )),
          ),
          Align(
            alignment: Alignment.center,
            child: InkWell(
              onTap: buttonOnClickStartRun,
              child: Container(
                alignment: Alignment.center,
                width: 150,
                height: 150,
                decoration: BoxDecoration(
                  image: DecorationImage(
                      image:
                          ExactAssetImage(ImageUtils.getImgPath("ic_pointer")),
                      fit: BoxFit.fill),
                ),
                child: Text("lotterys".tr,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: 15.sp,
                      color: const Color(0xFFD30000),
                    )),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
